//
//  HCNetworkTools.swift
//  Hweibome
//
//  Created by 何川 on 15/12/7.
//  Copyright © 2015年 hechuan. All rights reserved.
//

import UIKit
import AFNetworking

enum HCRequestMethod: String {
    case GET = "GET"
    case POST = "POST"
}

class HCNetworkTools: AFHTTPSessionManager {
    
    typealias HCNetworkToolsCallBack = (response:AnyObject?,error:NSError?)->()
    
    static let shareTools: HCNetworkTools =
    {
        let tools = HCNetworkTools()
         //有时候不提示,需要重新编译一下xcode
        tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        return tools
    }()
    
    /// 发送请求
    ///
    /// - parameter method:    请求方式
    /// - parameter urlString: 请求地址
    /// - parameter params:    请求参数
    /// - parameter callback:  请求成功之后的回调
    
    func request(method: HCRequestMethod,urlString:String , params:AnyObject? ,callback:HCNetworkToolsCallBack)
    {
        let succCallback = { (dataTasks:NSURLSessionDataTask,response: AnyObject) -> Void in
            callback(response: response, error: nil)
        }
        let failureCallBack = {(dataTasks:NSURLSessionDataTask?, error:NSError) -> Void in
            callback(response:nil , error:error)
        }
        
        if method == .GET{
            self.GET(urlString, parameters: params, success: succCallback, failure: failureCallBack)
        }else{
            self.POST(urlString, parameters: params, success: succCallback, failure: failureCallBack)

        }
    }
    
    
}

extension HCNetworkTools{
    
    func loadAccessToken(code:String , callback:HCNetworkToolsCallBack)
        {
    
            let urlString = "https://api.weibo.com/oauth2/access_token"
            let params = [
                "client_id": WB_APPKEY,
                "client_secret": WB_APP_SECRET,
                "grant_type": "authorization_code",
                "code": code,
                "redirect_uri": WB_REDIRECT_URI
    
            ]
            request(.POST, urlString: urlString, params: params, callback: callback)
            
    }
    
    func loadUserInfo (uid:String,accessToken:String,callback:HCNetworkToolsCallBack)
    {
        let urlString = "https://api.weibo.com/2/users/show.json"
        let params = [
        "access_token":accessToken,
            "uid":uid
        ]
        
        request(.GET, urlString: urlString, params: params, callback: callback)
    }

}

extension HCNetworkTools{
    func loadStatus(accessToken: String ,sinceId: Int64 = 0 ,maxid:Int64 = 0, callback:HCNetworkToolsCallBack){
        
    let urlString = "https://api.weibo.com/2/statuses/friends_timeline.json"
    let params = [
        "access_token":accessToken,
        "max_id":"\(maxid)",
        "since_id":"\(sinceId)"
    ]
    
    request(.GET, urlString: urlString, params: params, callback: callback)
        
    }
}
